import json
import os
from .models import db, ColumnModel

def register_cli(app):
    @app.cli.command("init-db")
    def init_db():
        """初始化数据库并导入栏目信息"""
        # 删除旧表并创建新表
        db.drop_all()
        db.create_all()
        print("数据库表已创建")

        # 导入栏目数据
        json_path = os.path.join(app.root_path, 'data', 'column_info.json')
        if not os.path.exists(json_path):
            print(f"错误：{json_path} 文件不存在！")
            return

        try:
            with open(json_path, 'r', encoding='utf-8') as f:
                data = json.load(f)
            
            if 'columns' not in data:
                print("错误：JSON 格式不正确，缺少 'columns' 键")
                return

            # 清空旧数据
            ColumnModel.query.delete()
            
            # 导入新数据
            for col in data['columns']:
                db.session.add(ColumnModel(
                    id=col['id'],
                    name=col['name'],
                    program_name=col['programName'],
                    editor='、'.join(col['editor']),
                    responsible_editor=col['responsibleEditor'],
                    broadcasters=','.join(col['broadcasters']),
                    director=col['director']
                ))
            
            db.session.commit()
            print(f"成功导入 {len(data['columns'])} 个栏目信息")

        except Exception as e:
            db.session.rollback()
            print(f"导入失败：{str(e)}")